package com.xiaoyi.springboot.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoyi.springboot.config.ResponseHelper;
import com.xiaoyi.springboot.config.ResponseModel;
import com.xiaoyi.springboot.entity.CommonUser;
import com.xiaoyi.springboot.entity.SysUser;
import com.xiaoyi.springboot.enums.ProductType;
import com.xiaoyi.springboot.enums.UserType;
import com.xiaoyi.springboot.service.CommonUserService;
import com.xiaoyi.springboot.service.RedisService;
import com.xiaoyi.springboot.shiro.JwtUtil;
import com.xiaoyi.springboot.util.CommonConstant;
import com.xiaoyi.springboot.util.PasswordUtil;
import com.xiaoyi.springboot.util.StringUtils;
import com.xiaoyi.springboot.vo.SysUserRepVo;
import com.xiaoyi.springboot.vo.UserLoginReqVo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoyi
 * @since 2021-10-10
 */
@RestController
@RequestMapping("/common-user")
public class CommonUserController {
  @Autowired
  private   CommonUserService commonUserService;
    @Autowired
    private RedisService redisService;
    @PostMapping("/list")
    public ResponseModel<List<CommonUser>> page(@RequestBody CommonUser commonUser,
                                                HttpServletRequest request) {
        List<CommonUser> list = commonUserService.list();
        return ResponseHelper.buildResponseModel(list);
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseModel<JSONObject> login(@RequestBody CommonUser commonUser){
        ResponseModel<JSONObject> result = new ResponseModel<JSONObject>();
        String username = commonUser.getUserName();
        String password = commonUser.getUserPassword();

        //1. 校验用户是否有效
        //update-begin-author:wangshuai date:20200601 for: 登录代码验证用户是否注销bug，if条件永远为false
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getUserAccount,username);
        CommonUser sysUser = commonUserService.getOne(queryWrapper);
        if (Objects.isNull(sysUser)){
            return ResponseHelper.validationFailure("用户名或密码错误");
        }

        //2. 校验用户名或密码是否正确
        String syspassword = sysUser.getUserPassword();
        if (!syspassword.equals(password)) {
            return ResponseHelper.validationFailure("用户名或密码错误");
        }
        //用户登录信息
        ;
        try {
            String token = JwtUtil.sign(username, syspassword, UserType.COMMONUSER.getValue());
            // 设置token缓存有效时间
            redisService.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisService.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            JSONObject obj = new JSONObject();
            obj.put("token", token);
            SysUserRepVo sysUserRepVo = new SysUserRepVo();
            BeanUtils.copyProperties(sysUser,sysUserRepVo);
            obj.put("userInfo", sysUserRepVo);
            return ResponseHelper.buildResponseModel(obj);
        } catch (UnsupportedEncodingException e) {
            return ResponseHelper.validationFailure("用户名或密码错误");
        }
    }
    // 用户添加,通过微信添加
    @RequestMapping(value = "/wechat-add", method = RequestMethod.POST)
    public ResponseModel<Object> add(@RequestBody CommonUser commonUser) {
        try {
            LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonUser::getUserAccount,commonUser.getUserAccount());
            List<CommonUser> list = commonUserService.list(queryWrapper);
            if(list.size()>1){
                return ResponseHelper.validationFailure("账号重复");
            }
            commonUser.setCreateTime(new Date());//设置创建时间

            // 通过微信鉴权的密码都是默认的
            commonUser.setUserPassword("123456");
            commonUser.setUserName("大名鼎鼎");
            commonUserService.save(commonUser);
            return ResponseHelper.buildResponseModel("添加成功");
        } catch (Exception e) {
            return ResponseHelper.validationFailure("添加失败");
        }
    }

    // 修改
    // 用户添加,通过微信添加
    @RequestMapping(value = "/wechat-update", method = RequestMethod.POST)
    public ResponseModel<Object> update(@RequestBody CommonUser commonUser) {
        try {
            LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonUser::getUserAccount,commonUser.getUserAccount());
            List<CommonUser> list = commonUserService.list(queryWrapper);
            if(list.size()<=0){
                return ResponseHelper.validationFailure("账号不存在");
            }
            CommonUser updateUser = list.get(0);

            BeanUtils.copyProperties(commonUser,updateUser);
            UpdateWrapper<CommonUser> updateWrapper = new UpdateWrapper<>();
            commonUserService.update(updateUser,updateWrapper);
            return ResponseHelper.buildResponseModel("添加成功");
        } catch (Exception e) {
            return ResponseHelper.validationFailure("添加失败");
        }
    }
    // 删除
    // 禁用






}
